{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c4ee9c68",
   "metadata": {},
   "source": [
    "## Streaming Real Time Options Data with ThetaData"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99836870",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install thetadata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d65a9f7",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "import datetime as dt\n",
    "from thetadata import ThetaClient, OptionRight, StreamMsgType, StreamResponseType"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99f61059",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def callback(msg):\n",
    "    # Handle received messages\n",
    "    if msg.type == StreamMsgType.TRADE:\n",
    "        print(\"----------------------------------------------------\")\n",
    "        print(f\"Contract: {msg.contract.to_string()}\")\n",
    "        print(f\"Trade: {msg.trade.to_string()}\")\n",
    "        print(f\"Last quote at time of trade: {msg.quote.to_string()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d03c0b74",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def stream_all_trades():\n",
    "    # Initialize the ThetaClient with your credentials\n",
    "    client = ThetaClient(username=\"YOUR_EMAIL\", passwd=\"YOUR_PASSWORD\")\n",
    "\n",
    "    # Connect to the data stream\n",
    "    client.connect_stream(callback)\n",
    "\n",
    "    # Request full trade stream for options\n",
    "    req_id = client.req_full_trade_stream_opt()\n",
    "\n",
    "    # Verify subscription\n",
    "    if client.verify(req_id) != StreamResponseType.SUBSCRIBED:\n",
    "        raise Exception(\"Unable to stream.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0fc2cb0",
   "metadata": {},
   "source": [
    "Start streaming all trades"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5723df3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "stream_all_trades()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f85fb8e4",
   "metadata": {},
   "source": [
    "Define parameters for a specific option contract"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48aa9934",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "ticker = \"SPY\"\n",
    "expiration_date = dt.date(2024, 12, 22)\n",
    "strike = 474"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ebfddf4",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def stream_contract():\n",
    "    # Initialize the ThetaClient with your credentials\n",
    "    client = ThetaClient(username=\"YOUR_EMAIL\", passwd=\"YOUR_PASSWORD\")\n",
    "\n",
    "    # Connect to the data stream\n",
    "    client.connect_stream(callback)\n",
    "\n",
    "    # Request trade stream for a specific option contract\n",
    "    req_id = client.req_trade_stream_opt(\n",
    "        ticker, expiration_date, strike, OptionRight.CALL\n",
    "    )\n",
    "\n",
    "    # Verify subscription\n",
    "    if client.verify(req_id) != StreamResponseType.SUBSCRIBED:\n",
    "        raise Exception(\"Unable to stream.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45e31a7d",
   "metadata": {},
   "source": [
    "Start streaming trades for a specific contract"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f13de806",
   "metadata": {},
   "outputs": [],
   "source": [
    "stream_contract()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "449ca05a",
   "metadata": {},
   "source": [
    "**Jason Strimpel** is the founder of <a href='https://pyquantnews.com/'>PyQuant News</a> and co-founder of <a href='https://www.tradeblotter.io/'>Trade Blotter</a>. His career in algorithmic trading spans 20+ years. He previously traded for a Chicago-based hedge fund, was a risk manager at JPMorgan, and managed production risk technology for an energy derivatives trading firm in London. In Singapore, he served as APAC CIO for an agricultural trading firm and built the data science team for a global metals trading firm. Jason holds degrees in Finance and Economics and a Master's in Quantitative Finance from the Illinois Institute of Technology. His career spans America, Europe, and Asia. He shares his expertise through the <a href='https://pyquantnews.com/subscribe-to-the-pyquant-newsletter/'>PyQuant Newsletter</a>, social media, and has taught over 1,000+ algorithmic trading with Python in his popular course **<a href='https://gettingstartedwithpythonforquantfinance.com/'>Getting Started With Python for Quant Finance</a>**. All code is for educational purposes only. Nothing provided here is financial advise. Use at your own risk."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
